package org.example.postgraduateproject.Servlet;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.postgraduateproject.Dao.AnswerDao;
import org.example.postgraduateproject.Dao.imp.AnswerDaoImp;
import org.example.postgraduateproject.entity.Answer;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wu
 * @date 2025-05-28
 * http://localhost:8080/postgraduateProject/answer.do?action=list
 */
@WebServlet("/answer.do")

public class AnswerServlet extends HttpServlet {
    private AnswerDao answerDao = new AnswerDaoImp();
    private Gson gson = new Gson();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        String action = req.getParameter("action");
        Map<String, Object> result = new HashMap<>();


        try {
            if (action == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: action");
                result.put("errorCode", 4001);
            } else {
                switch (action) {
                    case "list":
                        handleList(req, result);
                        break;
                    case "get":
                        handleGet(req, result);
                        break;
                    case "add":
                        handleAdd(req, result);
                        break;
                    case "update":
                        handleUpdate(req, result);
                        break;
                    case "delete":
                        handleDelete(req, result);
                        break;
                    case "accept":
                        handleAccept(req, result);
                        break;
                    case "vote":
                        handleVote(req, result);
                        break;
                    default:
                        result.put("success", false);
                        result.put("message", "未知操作类型");
                        result.put("errorCode", 4001);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器内部错误: " + e.getMessage());
            result.put("errorCode", 5000);
        }

        String json = gson.toJson(result);
        out.println(json);
        out.flush();
        out.close();
    }

    private void handleList(HttpServletRequest req, Map<String, Object> result) {
        Integer questionId = getIntParameter(req, "questionId");
        Integer userId = getIntParameter(req, "userId");

        List<Answer> answers;
        if (questionId != null) {
            answers = answerDao.selectAnswersByQuestionId(questionId);
        } else if (userId != null) {
            answers = answerDao.selectAnswersByUserId(userId);
        } else {
            answers = answerDao.selectAllAnswers();
        }

        result.put("success", true);
        result.put("message", "查询成功");
        result.put("data", answers);
    }

    private void handleGet(HttpServletRequest req, Map<String, Object> result) {
        Integer answerId = getIntParameter(req, "answerId");
        if (answerId == null) {
            result.put("success", false);
            result.put("message", "缺少参数answerId");
            result.put("errorCode", 4002);
            return;
        }

        Answer answer = answerDao.selectAnswerById(answerId);
        if (answer == null) {
            result.put("success", false);
            result.put("message", "回答不存在");
            result.put("errorCode", 4004);
        } else {
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", answer);
        }
    }

    private void handleAdd(HttpServletRequest req, Map<String, Object> result) {
        Integer questionId = getIntParameter(req, "questionId");
        Integer userId = getIntParameter(req, "userId");
        String content = req.getParameter("content");

        if (questionId == null || userId == null || content == null) {
            result.put("success", false);
            result.put("message", "缺少必要参数");
            result.put("errorCode", 4002);
            return;
        }

        Answer answer = new Answer();
        answer.setQuestionId(questionId);
        answer.setUserId(userId);
        answer.setContent(content);
        answer.setIsAccepted(false);
        answer.setVotes(0);

        int rows = answerDao.insertAnswer(answer);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "回答添加成功");
        } else {
            result.put("success", false);
            result.put("message", "回答添加失败");
            result.put("errorCode", 4005);
        }
    }

    private void handleUpdate(HttpServletRequest req, Map<String, Object> result) {
        Integer answerId = getIntParameter(req, "answerId");
        if (answerId == null) {
            result.put("success", false);
            result.put("message", "缺少参数answerId");
            result.put("errorCode", 4002);
            return;
        }

        Answer existingAnswer = answerDao.selectAnswerById(answerId);
        if (existingAnswer == null) {
            result.put("success", false);
            result.put("message", "回答不存在");
            result.put("errorCode", 4004);
            return;
        }

        String content = req.getParameter("content");

        if (content != null) existingAnswer.setContent(content);

        int rows = answerDao.updateAnswer(existingAnswer);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "回答更新成功");
        } else {
            result.put("success", false);
            result.put("message", "回答更新失败");
            result.put("errorCode", 4006);
        }
    }

    private void handleDelete(HttpServletRequest req, Map<String, Object> result) {
        Integer answerId = getIntParameter(req, "answerId");
        if (answerId == null) {
            result.put("success", false);
            result.put("message", "缺少参数answerId");
            result.put("errorCode", 4002);
            return;
        }

        int rows = answerDao.deleteAnswer(answerId);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "回答删除成功");
        } else {
            result.put("success", false);
            result.put("message", "回答删除失败或不存在");
            result.put("errorCode", 4007);
        }
    }

    private void handleAccept(HttpServletRequest req, Map<String, Object> result) {
        Integer answerId = getIntParameter(req, "answerId");
        Boolean isAccepted = getBooleanParameter(req, "isAccepted");

        if (answerId == null || isAccepted == null) {
            result.put("success", false);
            result.put("message", "缺少必要参数");
            result.put("errorCode", 4002);
            return;
        }

        Answer existingAnswer = answerDao.selectAnswerById(answerId);
        if (existingAnswer == null) {
            result.put("success", false);
            result.put("message", "回答不存在");
            result.put("errorCode", 4004);
            return;
        }

        existingAnswer.setIsAccepted(isAccepted);
        int rows = answerDao.updateAnswer(existingAnswer);

        if (rows > 0) {
            result.put("success", true);
            result.put("message", isAccepted ? "回答已采纳" : "回答已取消采纳");
        } else {
            result.put("success", false);
            result.put("message", "操作失败");
            result.put("errorCode", 4008);
        }
    }

    private void handleVote(HttpServletRequest req, Map<String, Object> result) {
        Integer answerId = getIntParameter(req, "answerId");
        Integer voteChange = getIntParameter(req, "voteChange");

        if (answerId == null || voteChange == null) {
            result.put("success", false);
            result.put("message", "缺少必要参数");
            result.put("errorCode", 4002);
            return;
        }

        Answer existingAnswer = answerDao.selectAnswerById(answerId);
        if (existingAnswer == null) {
            result.put("success", false);
            result.put("message", "回答不存在");
            result.put("errorCode", 4004);
            return;
        }

        existingAnswer.setVotes(existingAnswer.getVotes() + voteChange);
        int rows = answerDao.updateAnswer(existingAnswer);

        if (rows > 0) {
            result.put("success", true);
            result.put("message", "投票成功");
            result.put("newVoteCount", existingAnswer.getVotes());
        } else {
            result.put("success", false);
            result.put("message", "投票失败");
            result.put("errorCode", 4009);
        }
    }

    private Integer getIntParameter(HttpServletRequest req, String paramName) {
        String value = req.getParameter(paramName);
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private Boolean getBooleanParameter(HttpServletRequest req, String paramName) {
        String value = req.getParameter(paramName);
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        return Boolean.parseBoolean(value);
    }
}